package com.smm.web.vmc.api;

import com.smm.web.vmc.domain.Camera;
import com.smm.web.vmc.domain.Warehouse;
import com.smm.web.vmc.dto.JsonReturn;
import com.smm.web.vmc.service.CameraService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by zhenghao on 2016/9/30.
 *
 */
@Controller
@RequestMapping(value = "/api/camera")
public class CameraAPI {


    @Resource
    private CameraService cameraService;

    @RequestMapping(value = "/vdio.do",method = RequestMethod.GET)
    public ModelAndView vdio(int id){

        //获取摄像头信息
        Camera camera = cameraService.getOneById(id);

        //显示h5 播放页面
        ModelAndView mv = new ModelAndView("camera/vdio");

        mv.addObject("camera",camera);

        return mv;

    }


    @RequestMapping(value = "/listByUser.do",method = RequestMethod.POST)
    @ResponseBody
    public JsonReturn listByUser(int userId){

        List<Camera> cameraList = cameraService.getAllByUser(userId);

        //获取所有摄像头
//        List<Camera> cameraList = cameraService.getAll();

        try{

            if(cameraList==null || cameraList.size()==0) throw new Exception("没有可用的摄像头");

            //按仓库分组
            Map<Warehouse,List<Camera>> tempMap = cameraList.stream().collect(Collectors.groupingBy(Camera::getWarehouse));

            //组装数据
            List<CameraGroup> cameraGroups = new ArrayList<>();

            for(Warehouse warehouse:tempMap.keySet()){

                CameraGroup cameraGroup = new CameraGroup(warehouse,tempMap.get(warehouse));

                cameraGroups.add(cameraGroup);
            }


            return new JsonReturn(1,"success",cameraGroups);

        }catch (Exception e){

            e.printStackTrace();

            return new JsonReturn(0,e.getMessage());
        }

    }


    //分组数据对象
    class  CameraGroup{

        private Warehouse warehouse;

        private List<Camera> cameraList;

        public CameraGroup(Warehouse warehouse, List<Camera> cameraList) {
            this.warehouse = warehouse;
            this.cameraList = cameraList;
        }

        public Warehouse getWarehouse() {
            return warehouse;
        }

        public void setWarehouse(Warehouse warehouse) {
            this.warehouse = warehouse;
        }

        public List<Camera> getCameraList() {
            return cameraList;
        }

        public void setCameraList(List<Camera> cameraList) {
            this.cameraList = cameraList;
        }
    }



}
